354. Russian Doll Envelopes
题目描述
You have a number of envelopes with widths and heights given as a pair of integers (w, h). One envelope can fit into another if and only if both the width and height of one envelope is greater than the width and height of the other envelope.
What is the maximum number of envelopes can you Russian doll? (put one inside other)
Note:
Rotation is not allowed.
示例:
Input: [[5,4],[6,4],[6,7],[2,3]]
Output: 3
Explanation: The maximum number of envelopes you can Russian doll is 3 ([2,3] => [5,4] => [6,7]).
解答
遇见这种题一上来应该先排一下序,先按照套娃的宽度从小到大排序,如果宽度相同就按照高度从小到大排序。
这样就可以用DP的方法来求解了,DP数组中值最大的就是解(解法1)。
但是这道题还有一道更巧妙的解法:先按照套娃的宽度从小到大排序,如果宽度相同就按照高度从大到小排序。
然后这道题就转换称为高度的最长上升子序列问题(点击查看详解),最长上升子序列的长度就是解(解法2)。
代码
解法1
1 | class Solution { |
解法2
1 | class Solution { |